/*********************************************************************\
*
*                  (c) lkc
*                  All Rights Reserved. lkc Confidential
*
\*********************************************************************/
/*********************************************************************\
*   Title                      :
*
*   Module Description         :
*
*   Author                     : lkc
*
*   Created                    : 2018-7-24
*
\*********************************************************************/

#include "UDPSockQt.h"
#include "UtilityTH.h"

//const int PORT_NUM = 8888;

UDPSockQt::UDPSockQt(int port, QObject *parent)
    :CommBaseQt(parent),
      m_socket(this),
      m_portNum(port)
{
    //    m_socket.bind(QHostAddress::Any, PORT_NUM);
}

UDPSockQt::~UDPSockQt()
{
    printf("UDPSockQt derived() is called! Then close m_socket\n");
    Close();
}

bool UDPSockQt::Open()
{
    return m_socket.bind(QHostAddress::Any, m_portNum);
}

void UDPSockQt::Close()
{
    if(m_socket.isOpen())
    {
        m_socket.close();
    }
}

int UDPSockQt::Send(const unsigned char *sendBuf,int dataLen)
{
    if(!m_clientHasAddr)
    {
        DebugPrintf("has no client\n");
        return 0;
    }
    return m_socket.writeDatagram((char*)sendBuf,dataLen, m_clientAddress, m_clientPort);
}

int UDPSockQt::Read(unsigned char *readbuf, int dataLen)
{
    if(m_socket.hasPendingDatagrams())
    {
        int ret = m_socket.readDatagram((char*)readbuf, dataLen,&m_clientAddress,&m_clientPort);
        m_clientHasAddr = true;
        return ret;
    }
    else
    {
        return 0;
    }
}

/********************************************************************\
 *
 * REVISION RECORDS
 *
\*********************************************************************/
/*********************************************************************/
/*
 *
 *
 *
\*********************************************************************/
/*------------------------------The End------------------------------*/



